package cn.darkbox.sdk.zpdf;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;

import androidx.annotation.NonNull;

import java.io.File;

public class Utils {
    public static void executeOnPreDrawListener(@NonNull final View view, final Action action) {
        view.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                view.getViewTreeObserver().removeOnPreDrawListener(this);
                if (action != null) {
                    action.run();
                }
                return true;
            }
        });
    }


    public static boolean createDirectory(String path) {
        File directory = new File(path);
        if (directory.exists()) {
//            Log.w(TAG, "Directory '" + path + "' already exists");
            return false;
        }
        return directory.mkdirs();
    }


    public static Bitmap view2Bitmap(View view, int start, int end) {
        Bitmap clipBitmap = Bitmap.createBitmap(view.getWidth(), end - start,
                Bitmap.Config.ARGB_4444);
        clipBitmap.setDensity(view.getContext().getResources().getDisplayMetrics().densityDpi);
        Canvas canvaB = new Canvas(clipBitmap);

        if (start != 0) {
            canvaB.save();
            canvaB.translate(0, -start);
        }

        view.draw(canvaB);

        if (start != 0) {
            canvaB.restore();
        }
        return clipBitmap;
    }

    public static int dip2px(Context context, float dpValue) {
        if (context == null) {
            return 0;
        }
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale);
    }

    public static int px2dp(Context context, float dpValue) {
        if (context == null) {
            return 0;
        }
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue / scale);
    }

    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
        return (int) (spValue * fontScale + 0.5f);
    }
}
